﻿using System;
using System.IO;
using System.Security.Cryptography;

namespace AMing.Helper.Net40
{
    public class DESEncrypt
    {
        readonly string KEY_64 = "RZJ_User";
        readonly string IV_64 = "VavicApp"; //注意了，是8个字符，64位

        public DESEncrypt(string key_64, string iv_64)
        {
            KEY_64 = key_64;
            IV_64 = iv_64;
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Encode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);//加密钥匙转换为
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);//初始向量
            //二者共同影响加密后的数据
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();//加密算法的执行者
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();//这是向内存中写入的流
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);//用于加密的流
            //接入内存流
            //使用根据密匙和初始向量创建加密因子
            //通过加密流写入到内存中，在内村中以byte数组的形式存在

            StreamWriter sw = new StreamWriter(cst);//再将加密流接到文本流中
            sw.Write(data);//SW--->加密流----->内存流
            sw.Flush();//清除文本流
            cst.FlushFinalBlock();//清除加密流中的内容
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);//将内存中存在的byte【】数组，取出来，转换为经过加密的文本！

        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Decode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);//将密匙转换成二进制数组
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);//将初始初始向量转换成二进制数据

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);//将加过秘的文字转换成数组
            }
            catch
            {
                return null;
            }
            MemoryStream ms = new MemoryStream(byEnc);//将内存流接到上面去
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();//创建des加密算法执行类

            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);//解密流接到内存流上
            StreamReader sr = new StreamReader(cst);//文本读取流
            return sr.ReadToEnd();//加过秘的文字转化过来的数组------>内存流---------->解密流------------>原始文字
        }
    }
}